package com.yljk.yljkproject.aliyunface;

import static com.aliyun.aliyunface.ToygerConst.ZcodeConstants.ZCODE_NETWORK_ERROR;
import static com.aliyun.aliyunface.ToygerConst.ZcodeConstants.ZCODE_NETWORK_TIMEOUT;
import static com.aliyun.aliyunface.ToygerConst.ZcodeConstants.ZCODE_NET_INIT_ERROR;
import static com.aliyun.aliyunface.ToygerConst.ZcodeConstants.ZCODE_NET_UPLOAD_IMAGE_ERROR;
import static com.aliyun.aliyunface.ToygerConst.ZcodeConstants.ZCODE_NET_VERIFY_ERROR;
import static com.aliyun.aliyunface.ToygerConst.ZcodeConstants.ZCODE_NET_VERIFY_SUCCESS;
import static com.aliyun.aliyunface.ToygerConst.ZcodeConstants.ZCODE_OSS_TOKEN_INVALID;
import static com.aliyun.aliyunface.ToygerConst.ZcodeConstants.ZCODE_SYSTEM_EXC;
import static com.aliyun.aliyunface.ToygerConst.ZcodeConstants.ZCODE_USER_BACK;
import static com.aliyun.aliyunface.ToygerConst.ZcodeConstants.ZCODE_VERIFY_FAIL_PREFIX;
import static com.aliyun.aliyunface.ToygerConst.ZcodeConstants.ZCODE_ZIM_IS_BUSY;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alipay.deviceid.DeviceTokenClient;
import com.alipay.zoloz.toyger.ToygerLog;
import com.alipay.zoloz.toyger.face.ToygerFaceService;
import com.aliyun.aliyunface.ToygerConst;
import com.aliyun.aliyunface.ToygerPresenter;
import com.aliyun.aliyunface.WorkState;
import com.aliyun.aliyunface.api.AppDataProvider;
import com.aliyun.aliyunface.api.ZIMCallback;
import com.aliyun.aliyunface.api.ZIMCrashCallback;
import com.aliyun.aliyunface.api.ZIMFacade;
import com.aliyun.aliyunface.api.ZIMMetaInfo;
import com.aliyun.aliyunface.api.ZIMResponse;
import com.aliyun.aliyunface.api.ZIMRetCallback;
import com.aliyun.aliyunface.api.ZIMSession;
import com.aliyun.aliyunface.log.RecordLevel;
import com.aliyun.aliyunface.log.RecordService;
import com.aliyun.aliyunface.network.NetworkEnv;
import com.aliyun.aliyunface.network.NetworkStore;
import com.aliyun.aliyunface.ui.FaceLoadingActivity;
import com.aliyun.aliyunface.ui.OcrGuideFrontActivity;
import com.aliyun.aliyunface.ui.UICustomParams;
import com.yljk.yljkproject.R;

import net.security.device.api.SecurityDevice;
import net.security.device.api.SecurityInitListener;
import net.security.device.api.SecuritySession;

import java.util.HashMap;
import java.util.Map;

/**
 * Create By shicheng
 *
 * 阿里云人脸识别
 *
 */
public class MyZIMFacade {

    public static final String ZIM_EXT_PARAMS_KEY_SCREEN_ORIENTATION = "ext_params_key_screen_orientation";
    public static final String ZIM_EXT_PARAMS_VAL_SCREEN_PORT = "ext_params_val_screen_port";
    public static final String ZIM_EXT_PARAMS_VAL_SCREEN_LAND = "ext_params_val_screen_land";
    public static final String ZIM_EXT_PARAMS_KEY_USE_VIDEO = "ext_params_key_use_video";
    public static final String ZIM_EXT_PARAMS_VAL_USE_VIDEO_TRUE = "true";
    public static final String ZIM_EXT_PARAMS_VAL_USE_VIDEO_FALSE = "false";
    public static final String ZIM_EXT_PARAMS_KEY_OCR_BOTTOM_BUTTON_COLOR = "ext_params_key_ocr_bottom_button_color";
    public static final String ZIM_EXT_PARAMS_KEY_FACE_PROGRESS_COLOR = "ext_params_key_face_progress_color";
    public static final String ZIM_EXT_PARAMS_KEY_TOP_TIP_INDEX = "ext_params_key_top_tip_index";
    public static final String ZIM_EXT_PARAMS_KEY_TIP_INDEX_TT = "ext_params_key_tip_index_tt";
    private Context ctx;
    private boolean isBusy = false;
    private ZIMCallback zimCallback = null;

    protected MyZIMFacade(Context ctx) {
        this.ctx = ctx;
    }

    public void startOCR() {
        Intent intent = new Intent(this.ctx, OcrGuideFrontActivity.class);
        this.ctx.startActivity(intent);
    }

    public ZIMSession getSession() {
        SecuritySession securitySession = SecurityDevice.getInstance().getSession();
        String sessionContent = "";
        int sessonCode = -1;
        if (null != securitySession && 10000 == securitySession.code) {
            sessionContent = securitySession.session;
        }

        if (null != securitySession) {
            sessonCode = securitySession.code;
        }

        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "deviceTokenGetSession", new String[]{"code", "" + sessonCode, "session", sessionContent});
        ZIMSession zimSession = new ZIMSession();
        zimSession.code = sessonCode;
        zimSession.session = sessionContent;
        return zimSession;
    }

    public void verify(String zimId, boolean useMsgBox, ZIMCallback callback) {
        this.verify(zimId, useMsgBox, (HashMap)null, callback);
    }

    public void verify(String zimId, boolean useMsgBox, HashMap<String, String> extParams, ZIMCallback callback) {
        this.zimCallback = callback;
        ToygerPresenter.getInstance().setWorkState(WorkState.INIT);
        if (null == this.ctx) {
            this.sendResponse(ZCODE_SYSTEM_EXC);
        } else if (this.isBusy) {
            RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "zimBusy", new String[]{"status", "busy"});
            this.sendResponse(ZCODE_ZIM_IS_BUSY);
        } else {
            this.isBusy = true;
            final long verifyStartTime = System.currentTimeMillis();
            ToygerPresenter.getInstance().setZimId(zimId);
            ToygerPresenter.getInstance().setUseMsgBox(useMsgBox);
            RecordService.getInstance().init(this.ctx, zimId);
            ToygerPresenter.getInstance().setZimRetCallback(new ZIMRetCallback() {
                public void onZimFinish(String errCode) {
                    long verifyElapsedTime = System.currentTimeMillis() - verifyStartTime;
                    RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "verifyCost", new String[]{"cost", String.valueOf(verifyElapsedTime)});
                    MyZIMFacade.this.sendResponse(errCode);
                }
            });
            String topTipText;
            if (null != extParams && extParams.containsKey("ext_params_key_use_video")) {
                topTipText = (String)extParams.get("ext_params_key_use_video");
                if ("true".equalsIgnoreCase(topTipText)) {
                    ToygerPresenter.getInstance().setUseVideo(true);
                }
            }

            if (null != extParams && extParams.containsKey("ext_params_key_ocr_bottom_button_color") && extParams.containsKey("ext_params_key_face_progress_color")) {
                topTipText = (String)extParams.get("ext_params_key_ocr_bottom_button_color");
                if (!TextUtils.isEmpty(topTipText)) {
                    UICustomParams.OCR_BOTTOM_COLOR = topTipText;
                }

                String faceProgressColor = (String)extParams.get("ext_params_key_face_progress_color");
                if (!TextUtils.isEmpty(faceProgressColor)) {
                    UICustomParams.FACE_PROGRESS_COLOR = faceProgressColor;
                }
            }

            if (null != extParams && extParams.containsKey("ext_params_key_top_tip_index")) {
                topTipText = (String)extParams.get("ext_params_key_top_tip_index");
                if (!TextUtils.isEmpty(topTipText) && null != topTipText && topTipText.equalsIgnoreCase("ext_params_key_tip_index_tt")) {
                    UICustomParams.TOP_TIP_TEXT = this.ctx.getString(R.string.tantan_top_tip_text);
                }
            }

            topTipText = getMetaInfos(this.ctx);
            Intent intent = new Intent(this.ctx, MyFaceLoadingActivity.class);
            intent.putExtra("toyger_meta_info", topTipText);
            if (null != extParams && extParams.containsKey("ext_params_key_screen_orientation")) {
                intent.putExtra("ext_params_key_screen_orientation", (String)extParams.get("ext_params_key_screen_orientation"));
            }

            this.ctx.startActivity(intent);
            ((Activity)this.ctx).overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        }
    }

    public void destroy() {
    }

    public static void installIPv6(Context context) {
        if (null != context) {
            if (null == ToygerPresenter.getInstance().getNetworkEnv()) {
                NetworkEnv networkEnv = new NetworkEnv();
                networkEnv.safUrl = "https://cloudauth-dualstack.aliyuncs.com";
                networkEnv.deviceUrl = "https://cloudauth-dualstack.aliyuncs.com";
                networkEnv.appKey = "LTAI4FnprqBfKVt1yjs23kY9";
                networkEnv.appSecret = "hKDBzWfxSNRSq0K8MVTJyCsJ1HeR93hfnxyRkcam9YY=";
                ToygerPresenter.getInstance().setNetworkEnv(networkEnv);
            }

            String appPkgName = context.getPackageName();
            RecordService.getInstance().init(context, appPkgName);
            final long alipayDeviceStartTime = System.currentTimeMillis();
            DeviceTokenClient.getInstance(context).initToken("zorro", "elBwppCSr9nB1LIQ", new DeviceTokenClient.InitResultListener() {
                public void onResult(String token, int errorCode) {
                    long alipayInitElapsedTime = System.currentTimeMillis() - alipayDeviceStartTime;
                    RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "AlipayDeviceInitCost", new String[]{"cost", String.valueOf(alipayInitElapsedTime)});
                    RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "AlipayDevice", new String[]{"code", "" + errorCode, "token", "" + token});
                    if (0 == errorCode) {
                        ToygerPresenter.getInstance().setAlipayDeviceToken(token);
                    } else {
                        ToygerPresenter.getInstance().setAlipayDeviceToken("");
                    }

                }
            });
            final long aliyunDeviceStartTime = System.currentTimeMillis();
            SecurityDevice.getInstance().initV6(context, "3f99f9a44d7bfd84458637ae6be5000a", new SecurityInitListener() {
                public void onInitFinish(int i) {
                    long aliyunInitElapsedTime = System.currentTimeMillis() - aliyunDeviceStartTime;
                    RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "AliyunDeviceInitCost", new String[]{"cost", String.valueOf(aliyunInitElapsedTime)});
                    if (10000 == i) {
                        RecordService.getInstance().recordEvent(RecordLevel.LOG_ERROR, "deviceTokenInitSuccess", new String[]{"status", "true"});
                    } else {
                        RecordService.getInstance().recordEvent(RecordLevel.LOG_ERROR, "deviceTokenInitFail", new String[]{"status", "true", "errCode", String.valueOf(i)});
                    }

                }
            });
            long faceModelLoadStart = System.currentTimeMillis();
            ToygerFaceService.preLoad(context);
            long faceModelLoadElapsed = System.currentTimeMillis() - faceModelLoadStart;
            RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "toygerModelLoadCost", new String[]{"cost", String.valueOf(faceModelLoadElapsed)});
        }
    }

    public static void install(Context context) {
        if (null != context) {
            if (null == ToygerPresenter.getInstance().getNetworkEnv()) {
                NetworkEnv networkEnv = new NetworkEnv();
                networkEnv.safUrl = "https://cloudauth.aliyuncs.com";
                networkEnv.deviceUrl = "https://cloudauth.aliyuncs.com";
                networkEnv.appKey = "LTAI4FnprqBfKVt1yjs23kY9";
                networkEnv.appSecret = "hKDBzWfxSNRSq0K8MVTJyCsJ1HeR93hfnxyRkcam9YY=";
                ToygerPresenter.getInstance().setNetworkEnv(networkEnv);
            }

            String appPkgName = context.getPackageName();
            RecordService.getInstance().init(context, appPkgName);
            final long alipayDeviceStartTime = System.currentTimeMillis();
            DeviceTokenClient.getInstance(context).initToken("zorro", "elBwppCSr9nB1LIQ", new DeviceTokenClient.InitResultListener() {
                public void onResult(String token, int errorCode) {
                    long alipayInitElapsedTime = System.currentTimeMillis() - alipayDeviceStartTime;
                    RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "AlipayDeviceInitCost", new String[]{"cost", String.valueOf(alipayInitElapsedTime)});
                    RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "AlipayDevice", new String[]{"code", "" + errorCode, "token", "" + token});
                    if (0 == errorCode) {
                        ToygerPresenter.getInstance().setAlipayDeviceToken(token);
                    } else {
                        ToygerPresenter.getInstance().setAlipayDeviceToken("");
                    }

                }
            });
            final long aliyunDeviceStartTime = System.currentTimeMillis();
            SecurityDevice.getInstance().init(context, "3f99f9a44d7bfd84458637ae6be5000a", new SecurityInitListener() {
                public void onInitFinish(int i) {
                    long aliyunInitElapsedTime = System.currentTimeMillis() - aliyunDeviceStartTime;
                    RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "AliyunDeviceInitCost", new String[]{"cost", String.valueOf(aliyunInitElapsedTime)});
                    if (10000 == i) {
                        RecordService.getInstance().recordEvent(RecordLevel.LOG_ERROR, "deviceTokenInitSuccess", new String[]{"status", "true"});
                    } else {
                        RecordService.getInstance().recordEvent(RecordLevel.LOG_ERROR, "deviceTokenInitFail", new String[]{"status", "true", "errCode", String.valueOf(i)});
                    }

                }
            });
            long faceModelLoadStart = System.currentTimeMillis();
            ToygerFaceService.preLoad(context);
            long faceModelLoadElapsed = System.currentTimeMillis() - faceModelLoadStart;
            RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "toygerModelLoadCost", new String[]{"cost", String.valueOf(faceModelLoadElapsed)});
        }
    }

    private static ZIMMetaInfo getZimMetaInfo(Context context) {
        return getZimMetaInfo(context, (Map)null);
    }

    private static ZIMMetaInfo getZimMetaInfo(Context context, Map<String, Object> params) {
        AppDataProvider appDataProvider = new AppDataProvider() {
            public String getApdidToken(Context context) {
                return MyZIMFacade.getApDidToken(context);
            }

            public String getDeviceType() {
                return "android";
            }

            public String getDeviceModel() {
                return Build.MODEL;
            }

            public String getAppName(Context context) {
                return context == null ? "" : context.getPackageName();
            }

            public String getAppVersion(Context context) {
                String versionName = "";

                try {
                    PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
                    versionName = info.versionName;
                } catch (PackageManager.NameNotFoundException var4) {
                    ToygerLog.w(var4);
                }

                return versionName;
            }

            public String getOsVersion() {
                return Build.VERSION.RELEASE;
            }
        };
        ZIMMetaInfo zimMetaInfo = new ZIMMetaInfo();
        zimMetaInfo.setApdidToken(appDataProvider.getApdidToken(context));
        zimMetaInfo.setAppName(appDataProvider.getAppName(context));
        zimMetaInfo.setAppVersion(appDataProvider.getAppVersion(context));
        zimMetaInfo.setDeviceModel(appDataProvider.getDeviceModel());
        zimMetaInfo.setDeviceType(appDataProvider.getDeviceType());
        zimMetaInfo.setOsVersion(appDataProvider.getOsVersion());
        zimMetaInfo.setBioMetaInfo("6.2.1:11501568,4");
        zimMetaInfo.setZimVer("1.0.0");
        zimMetaInfo.setSdkVersion("1.4.2");
        return zimMetaInfo;
    }

    public static String getMetaInfos(Context context) {
        return getMetaInfos(context, (Map)null);
    }

    public static String getMetaInfos(Context context, Map<String, Object> params) {
        return getMetaInfos(context, params, true);
    }

    private static String getMetaInfos(Context context, Map<String, Object> params, boolean needInit) {
        String metaInfos = "";

        try {
            ZIMMetaInfo zimMetaInfo = getZimMetaInfo(context, params);
            metaInfos = JSON.toJSONString(zimMetaInfo);
        } catch (Throwable var5) {
            ToygerLog.e(var5);
        }

        return metaInfos;
    }

    private static String getApDidToken(Context context) {
        String apDidToken = ToygerPresenter.getInstance().getAlipayDeviceToken();
        if (TextUtils.isEmpty(apDidToken)) {
            apDidToken = "";
        }

        return apDidToken;
    }

    private void sendResponse(String errCode) {
        if (TextUtils.isEmpty(errCode)) {
            errCode = ZCODE_SYSTEM_EXC;
        }

        if (null != this.zimCallback) {
            ZIMResponse zimResponse = new ZIMResponse();
            zimResponse.reason = errCode;
            zimResponse.deviceToken = ToygerPresenter.getInstance().getAliyunDeviceToken();
            if (ToygerPresenter.getInstance().getUseVideo()) {
                zimResponse.videoFilePath = ToygerPresenter.getInstance().getVideoFilePath();
            }

            if (errCode.equalsIgnoreCase(ZCODE_NET_VERIFY_SUCCESS)) {
                zimResponse.code = 1000;
            } else if (errCode.startsWith(ZCODE_VERIFY_FAIL_PREFIX)) {
                String[] errs = errCode.split("_");
                if (2 == errs.length) {
                    zimResponse.reason = errs[1];
                }

                zimResponse.code = 2006;
            } else if (!errCode.equalsIgnoreCase(ZCODE_NET_INIT_ERROR) && !errCode.equalsIgnoreCase(ZCODE_NET_UPLOAD_IMAGE_ERROR) && !errCode.equalsIgnoreCase(ZCODE_NET_VERIFY_ERROR) && !errCode.equalsIgnoreCase(ZCODE_NETWORK_TIMEOUT) && !errCode.equalsIgnoreCase(ZCODE_NETWORK_ERROR) && !errCode.equalsIgnoreCase(ZCODE_OSS_TOKEN_INVALID)) {
                if (errCode.equalsIgnoreCase(ZCODE_USER_BACK)) {
                    zimResponse.code = 1003;
                } else if (errCode.equalsIgnoreCase(String.valueOf(2003))) {
                    zimResponse.code = 2003;
                } else {
                    zimResponse.code = 1001;
                }
            } else {
                zimResponse.code = 2002;
            }

            this.zimCallback.response(zimResponse);
        }

        this.isBusy = false;
    }

    public static void reportCrash(String content, ZIMCrashCallback zimCrashCallback) {
        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "appCrash", new String[]{"crashInfo", content});
        RecordService.getInstance().reportCrash(zimCrashCallback);
    }

    public static Map getNetStore() {
        return NetworkStore.getInstance().get();
    }

    public static void setNetworkEnv(NetworkEnv networkEnv) {
        ToygerPresenter.getInstance().setNetworkEnv(networkEnv);
    }

    public static NetworkEnv getNetworkEnv() {
        return ToygerPresenter.getInstance().getNetworkEnv();
    }
    
}
